import { defineStore } from 'pinia'
import api from '@/api/request'
import storage from 'localforage'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      avatar: '',
      name: '',
      userSidebar: []
    }
  }),
  actions: {
    login (userInfo) {
      return new Promise((resolve, reject) => {
        api.mockRequest('user.login', userInfo).then(res => {
          const tokenValue = res.data.access_token
          storage.setItem('OAuthToken', tokenValue)
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 登出
    logout () {
      return api.mockRequest('user.logout').then(() => {
        storage.removeItem('OAuthToken')
      })
    },
    // 获取用户信息
    getInfo () {
      return api.mockRequest('user.info').then(res => {
        this.userInfo = res.data
      })
    }
  }
})